#include<iostream>
#include<vector>

using namespace std;

long long maxWater(vector<int>& arr) {
    int nmax = arr[0], n = arr.size();
    vector<int> l(n);
    auto r = l;
    for (int i = 1; i < n - 1; i++)
    {
        l[i] = nmax;
        nmax = max(nmax, arr[i]);
    }
    nmax = arr[n - 1];
    for (int i = n - 2; i > 0; i--)
    {
        r[i] = nmax;
        nmax = max(nmax, arr[i]);
    }

    long long res = 0;
    for (int i = 1; i < n - 1; i++)
    {
        long long t = min(l[i], r[i]);
        if (t > arr[i])
        {
            res += t - arr[i];
        }
    }
    return res;
}

